package com.wei.shopping.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.wei.shopping.entrty.Result;
import com.wei.shopping.pojo.Commodity;
import com.wei.shopping.pojo.Notices;
import com.wei.shopping.pojo.Sold;
import com.wei.shopping.pojo.UserInfo;
import com.wei.shopping.service.CommService;
import com.wei.shopping.service.NoticesService;
import com.wei.shopping.service.SoldService;
import com.wei.shopping.service.UserService;
import com.wei.shopping.utils.KeyUtil;
import org.apache.catalina.User;
import org.apache.shiro.web.session.HttpServletSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * 支付Controller
 */
@Controller
@RequestMapping("/alipay")
public class AlipayController {
    private final String APP_ID = "2021000117658157";
    private final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCKPlk+sLT6FVAsHV9T91L2QQS4LO0Zi+J1YCcfn0R3/kQVSUCVvmQLE+oUuloxrSpgCbkZgd/eJLudvvFCuJRUg8HZdqRhH+/yKXuPA+J3gRFoIpQ0mRagpfmpFtPlit5xcKsA/Cz3jNmGhk1F6FNaHvjOvmWdzrs6Q13Ykp+IqvT+2Sb31Ru02eYh6xFOJkdiCwEDCbcD1OSMLbj9iAs1xBrzl8NrfarOtcXIxbYuQy/JhDpx1jz/2nwLJ1GBC+wZGr52YuLphwZzA4rFh2QEVRlQI1kAHH7b3DnXXEddufVfUKpSwdfvFhRbNdGwXZZSfeVHiop7GBjK/0Is5nvhAgMBAAECggEAHQZ6Nm9jkB5pdtmz6i1DffCozQKhxXtZUMufa0RFW+xG3zFCHi6bUrgbrb5ysXtqKj/gXTqnhjywJ66veRLIEf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W1n9N6c414v0JYK3uZKINHVkRS9bL05kqBP2R2pFnyzd8FTRwY7VFqP38Yss=";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuTA433YDCnQ2wTNjGlM4NdKWzO2WLH27VBuslYdqSxHKoCNAxK1W+8XSXKxhplS/B1Hdsz20XqdfVdYkeenc6SxpSA2iXLR8zwJ2W8/ZWeFZbe2P5RJFcjOqPcYeOoVCXAgIC2jb3bhNadeeNq23I2YAehe42Eq4sODPDdgi+5Np8JiZhNZmzNfys4xswcH/d8X8ZFcXMkbSanKtTHpWUwd6q96rAr358+Gty80bPY1X53xhOQfOkloxMZq4GpRQsOKFnecOCiaDxCGAi+gykdzf3/HabZuO0yzZB1O6prL/aMy5lzLYpVMD+URkX7bHv9Y/iTdo3IZH3lTRFW17TQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "ttp://9ueazmu.nat.ipyingshe.com/alipay/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://9ueazmu.nat.ipyingshe.com/alipay/returnUrl";

    @Resource
    private CommService commService;
    @Resource
    private SoldService soldService;
    @Resource
    private NoticesService noticesService;
    @Resource
    private UserService userService;
    @RequestMapping("alipay")
    public void alipay(HttpServletResponse httpResponse, @RequestParam("commid") String commid,HttpSession session) throws IOException {

        String userid =(String) session.getAttribute("userid");
        Commodity commodity = commService.findById(commid);
        System.out.println("alipay：" + commodity);
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = commodity.getCommid()+"-"+userid;
        //付款金额，必填
        String total_amount =commodity.getThinkmoney().toString();
        //订单名称，必填
        String subject = commodity.getCommname();
        //商品描述，可空
        String body = commodity.getCommdesc();
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额=" + total_amount);

            String commid = out_trade_no.split("-")[0];
            String userid = out_trade_no.split("-")[1];
            //获取用户详情信息
            UserInfo userinfo = userService.findById(userid);
            Commodity commodity = commService.findById(commid);
            UserInfo userinfo2 = userService.findById(commodity.getUserid());
            System.out.println("userid:"+userid);
            System.out.println("commuserid:"+userinfo2.getUserid());
            //设置销售记录
            Sold sold = new Sold();
            sold.setCommid(commodity.getCommid());
            sold.setId(KeyUtil.genUniqueKey());
            sold.setUserid(userid);
            sold.setCommdesc(commodity.getCommdesc());
            sold.setCommname(commodity.getCommname());
            sold.setSoldmoney(commodity.getThinkmoney());
            sold.setCategory(commodity.getCategory());
            sold.setCommuserid(commodity.getUserid());
            //设置卖家通知信息
            Notices notices = new Notices();
            notices.setId(KeyUtil.genUniqueKey());
            notices.setTpname("商品售出");
            notices.setWhys("你的商品："+ commodity.getCommname()+",已售出。买家："+userinfo.getUsername()+",联系方式："+userinfo.getMobilephone()+",请尽快联系。");
            notices.setUserid(commodity.getUserid());
            //设置买家通信息
            Notices notices2 = new Notices();
            notices2.setId(KeyUtil.genUniqueKey());
            notices2.setTpname("商品购买");
            notices2.setWhys("你已购买商品："+ commodity.getCommname()+"。卖家："+userinfo2.getUsername()+",联系方式："+userinfo2.getMobilephone()+",请尽快联系。");
            notices2.setUserid(userid);
            //设置商品信息
            commodity.setCommstatus(4);
            try{
                //添加销售记录
                soldService.addSold(sold);
                //通知用户商品售出
                noticesService.addnotices(notices);
                noticesService.addnotices(notices2);
                //修改商品信息为已售出
                commService.updatestatus(4,commodity.getCommid());
                return "redirect:http://localhost:8181/";
            }catch(Exception e){
                e.printStackTrace();
                return "/error/404";
            }
            //支付成功，修复支付状态
            //payService.updateById(Integer.valueOf(out_trade_no));
        }else{
            return "/commodity/no";//跳转付款失败页面
        }

    }
}
